package com.example.myys.network.ysPlugins

import android.annotation.SuppressLint
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONArray
import com.alibaba.fastjson2.JSONObject
import com.example.myys.Constants
import com.example.myys.common.DataSource
import com.example.myys.data.entity.ChapterBean
import com.example.myys.data.entity.DataBean
import com.example.myys.network.HttpClient
import com.example.myys.network.PluginInterface

class JqqYsParse : PluginInterface {
    override suspend fun getRecommend(
        baseUrl: String,
        type: String,
        rules: JSONObject
    ): List<DataBean> {
        var jqqYsDataList= ArrayList<DataBean>()
            val url="$baseUrl/api.php/provide/vod/?ac=videolist"
            val responseBody = HttpClient.get(url, mapOf())
            if(responseBody!=null){
                val responJson = JSON.parseObject(responseBody)
                val jsonArray = responJson.getJSONArray("list")
                jqqYsDataList+=setListData(jsonArray,baseUrl)
            }
        return jqqYsDataList
    }

    @SuppressLint("SuspiciousIndentation")
    override suspend fun getCategorize(
        baseUrl: String,
        categorizeName: String,
        type: String,
        page: Int,
        rules: JSONObject
    ): List<DataBean> {
        var jqqYsDataList= ArrayList<DataBean>()
        val urls = rules.getJSONArray("urls") //获取链接
        val urlitems =
            urls.filter { url -> JSONObject.from(url).getString("name") == categorizeName }
        if (urlitems.isEmpty()) {
            return jqqYsDataList
        }
        val typeItem = JSONObject.from(urlitems[0]).getString("parameters")

        val typeLists = typeItem?.split(",")
            if (typeLists != null&&baseUrl!=null) {
                for (typeItems in typeLists){
                    val url = "$baseUrl/api.php/provide/vod/?ac=videolist&t=${typeItems}&pg=${page}"
                    val responseBody = HttpClient.get(url, mapOf())
                    if(responseBody!=null){
                        val responJson = JSON.parseObject(responseBody)
                        val jsonArray = responJson.getJSONArray("list")
                        jqqYsDataList+=setListData(jsonArray,baseUrl)
                    }
                }
            }

        return jqqYsDataList.sortedByDescending { it.updateTime }
    }

    override suspend fun getSearchKeyWord(
        baseUrl: String,
        type: String,
        keyword: String,
        rules: JSONObject
    ): List<DataBean> {
        var jqqYsDataList= ArrayList<DataBean>()
        val url = "$baseUrl/api.php/provide/vod/?ac=videolist&wd=${keyword}"
        val responseBody = HttpClient.get(url, mapOf())
        if (responseBody != null) {
            val responJson = JSON.parseObject(responseBody)
            val jsonArray = responJson.getJSONArray("list")
            jqqYsDataList += setListData(jsonArray, baseUrl)
        }

        return jqqYsDataList
    }

    override suspend fun getDetails(
        baseUrl: String,
        dataBean: DataBean,
        rules: JSONObject
    ): DataBean {
        var jqqYsDataList = ArrayList<DataBean>()
        val responseBody = HttpClient.get(dataBean.url.replace("BB", "&"), mapOf())
        if (responseBody != null) {
            val responJson = JSON.parseObject(responseBody)
            val jsonArray = responJson.getJSONArray("list")
            jqqYsDataList += setListData(jsonArray, baseUrl)
        }
        return jqqYsDataList.get(0)
    }

    override suspend fun getContent(baseUrl: String, url: String, rules: JSONObject): String {
        return url
    }

    fun setListData(jsonArray: JSONArray, baseUrl: String): ArrayList<DataBean> {
        var jqqYsDataList = ArrayList<DataBean>()
        if (jsonArray != null) {
            for (jsonItem in jsonArray) {
                var jqqDataBean: DataBean = DataBean()
                val videoItem = JSONObject.from(jsonItem)
                val urlList = videoItem.getString("vod_play_url")
                //播放地址分割
                var splits = urlList.split("$$$")
                var split: List<String> = arrayListOf()

                jqqDataBean.name = videoItem.getString("vod_name")
                jqqDataBean.url =
                    "${baseUrl}/api.php/provide/vod/?ac=videolistBBids=${videoItem.get("vod_id")}"
                jqqDataBean.category = videoItem.getString("vod_class")
                jqqDataBean.status = videoItem.getString("vod_remarks")
                jqqDataBean.type = Constants.YS
                jqqDataBean.cover = videoItem.getString("vod_pic")
                jqqDataBean.author = videoItem.getString("vod_actor")
                jqqDataBean.desc = videoItem.getString("vod_content")
                jqqDataBean.score = videoItem.getString("vod_douban_score")
                jqqDataBean.chapterCount = videoItem.getString("vod_total")
                jqqDataBean.releaseTime = videoItem.getString("vod_pubdate")
                jqqDataBean.updateTime = videoItem.getString("vod_time")
                val dataSources = ArrayList<DataSource>()
                for ((indexs, splitItem) in splits.withIndex()) {
                    val jsChapterList = ArrayList<ChapterBean>()
                    split = splitItem.split("#")
                    for ((index, js) in split.withIndex()) {
                        val jsChapter = ChapterBean()
                        jsChapter.index = index
                        val jsList = js.split("$")
                        if (jsList.isNotEmpty() && jsList.size > 1) {
                            jsChapter.name = jsList[0]
                            jsChapter.url = jsList[1]
                        }
                        jsChapterList.add(jsChapter)
                    }
                    jqqDataBean.chapters = jsChapterList
                    dataSources.add(DataSource(indexs, "默认${indexs}", indexs, jsChapterList))
                }
                jqqDataBean.dataSource = dataSources
                jqqYsDataList.add(jqqDataBean)
            }
        }
        return jqqYsDataList
    }


}

/*
可用于获取分类、列表和详情
ac：模式（videolist或detail详细模式），为空＝列表标准模式
ids: 影片id，多个使用,隔开
t: 类型
h：最近多少小时内
pg: 页数
wd：搜索like
at：输出格式，可选xml
# 取最新列表带分类
/api.php/provide/vod/
# 取详细列表不带分类
/api.php/provide/vod/?ac=videolist
# 取特定分类
/api.php/provide/vod/?ac=videolist&t=2
# 取某影片数据
/api.php/provide/vod/?ac=videolist&ids=33317*/
